<?php

//defined( '_VALID_MOS' ) or die( 'Restricted access' );


define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) . "/../t2" );
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();

$mainframe->route();
$user =& JFactory::getUser();



$categoryid=0;

require "jumi_dbconfig.php";

$this_username = $user->username;
$this_useremail = $user->email;
$this_userid = $user->id;
$this_usertype = $user->usertype;


function SendCommandSF($command,$para1,$para2,$para3 ) {
    switch ($command)
    {
	case "POST":
		return PostStory(urldecode($para1),urldecode($para2),urldecode($para3) );	
		break;
	case "UP":
		return Vote("UP",$para1);	
		break;
	case "DOWN":
		return Vote("DOWN",$para1);	
		break;
	case "HIDE":
		return Admin("HIDE",$para1);	
		break;


    }
    return "OK";
}

function Admin($mode, $commentid)
{
	global $this_username;
	global $this_userid;
	global $categoryid;
	global $db;
	if ($this_username =="" )
	{
		return "NOTLOGIN";
	}
	switch ( $mode )
	{
		case "HIDE":
			$published=0;
			break;
		case "SHOW":
			$published=1;
			break;
	} 
	
	$query = sprintf("update comment set published=%d where id=%d or parentid=%d ",
		$published,$commentid,$commentid);
	try  {
		$result = mysql_query("$query",$db) ;
	}
 	catch (Exception $e)
	{
		return "ADMINFAILED:$commentid";
	}
	return "ADMINOK:$commentid";
}

function Vote($mode, $commentid)
{
	global $this_username;
	global $this_userid;
	global $categoryid;
	global $db;
	if ($this_username =="" )
	{
		return "NOTLOGIN";
	}
	switch ( $mode )
	{
		case "UP":
			$up=1;
			$down=0;
			break;
		case "DOWN":
			$up=0;
			$down=1;
	} 
	
	$query= "delete from comment_vote where commentid=$commentid and userid=$this_userid ";
	$result = mysql_query("$query",$db) ;
	$query = sprintf("INSERT INTO comment_vote (commentid,userid,up_vote,down_vote) VALUES ('%d','%d','%d','%d')",
		$commentid,$this_userid,$up,$down );
	try  {
		$result = mysql_query("$query",$db) ;
	}
 	catch (Exception $e)
	{
		return "VOTEFAILED:$commentid";
	}
	return "VOTEOK:$commentid";
}
function PostStory($title,$desc,$link)
{
	global $this_username;
	global $this_userid;
	global $categoryid;
	global $db;

	if ( strlen( $link)> 15 )
	{
	// new code to parse youtube url.

		$urlhost=parse_url($link, PHP_URL_HOST);
		if ( strpos($urlhost,"youtube.com" ) === false )
		{
			return "FAILED:INVALIDLINK";
		}
		$var=parse_url($link,PHP_URL_QUERY);
		$var  = html_entity_decode($var);
		$var  = explode('&', $var);
		
		$youtubeid="";
		foreach($var as $val)
		{
			$x = explode('=', $val);
			if ( $x[0] == "v" )
			{
				$youtubeid=$x[1];
				break;
			}
		}
		if ( $youtubeid == "" )
			return "FAILED:INVALIDLINK";
		else
			$link=$youtubeid;
	}
	$query = sprintf("INSERT INTO  critizethis_story (categoryid,title,description,link,published) VALUES ('%d','%s','%s','%s',0)",
		mysql_real_escape_string($categoryid),
		mysql_real_escape_string($title),
		mysql_real_escape_string($desc),
		mysql_real_escape_string($link) );
	try  {
		$result = mysql_query("$query",$db) or die ("Error in query: $query. " . mysql_error());
	}
 	catch (Exception $e)
	{
		return "FAILED:DB";
	}
	return "OK";
}


    require("sajax/sajax.php");
//    $sajax_debug_mode = true;

    $sajax_failure_redirect = "http://sajax.info/sajaxfail.html";
    sajax_export("SendCommandSF");
    sajax_handle_client_request();

header("Pragma: no-cache");

?>
<html>
<head>
<link rel=StyleSheet href="criticizethis.css" type="text/css">
</head>
<body>


<script type="text/javascript" src="sajax/json2.stringify.js"></script>
<script type="text/javascript" src="sajax/json_stringify.js"></script>
<script type="text/javascript" src="sajax/json_parse_state.js"></script>
<script type="text/javascript" src="sajax/sajax.js"></script>

<script>

<?
	sajax_show_javascript();
?>
function FIND(item) {
   if( window.mmIsOpera ) return(document.getElementById(item));
   if (document.all) return(document.all[item]);
   if (document.getElementById) return(document.getElementById(item));
   return(false);
};

function SendCommand_callback( result) {
	
        if ( result == "NOTLOGIN" )
        {
		mymessage.innerHTML="Please login first.";
        }
        if ( result == "OK" )
        {
		mytitle.value="";
		mydesc.value="";
		mylink.value="";
		mymessage.innerHTML="Story submitted, it will be shown after approved by Admin.";
		window.location.reload();
        }
        if ( result.indexOf("FAILED:")== 0 )
	{
		start=result.indexOf (":")+1;
		reason=result.substr(start,result.length-start );
		switch ( reason)
		{
			case "DB":
				mymessage.innerHTML="Failed to submit.";
				break;
			case "INVALIDLINK":
				mymessage.innerHTML="Invalid link. must be a youtube id or youtube url.";
				break;
			default:
				mymessage.innerHTML=result;
				break;
		}

	}
        if ( result.indexOf("VOTEOK:")== 0 )
        {
		start=result.indexOf (":")+1;
		commentid=result.substr(start,result.length-start );
		obj=FIND("mymessage_" + commentid );
		//alert(commentid);
		obj.innerHTML="Vote OK. ";
		window.location.reload();
	}
        if ( result.indexOf("VOTEFAILED:")== 0 )
        {
		start=result.indexOf (":")+1;
		commentid=result.substr(start,result.length-start );
		obj=FIND("mymessage_" + commentid );
		obj.innerHTML="Vote failed. You can't vote twice on same comment.";
	}
        if ( result.indexOf("ADMINOK:")== 0 )
        {
		start=result.indexOf (":")+1;
		commentid=result.substr(start,result.length-start );
		obj=FIND("mymessage_" + commentid );
		//alert(commentid);
		obj.innerHTML="Comment hidden. ";
		window.location.reload();
	}
}

function SendCommand(command, para1,para2,para3)
{
        x_SendCommandSF(command, para1,para2, para3, SendCommand_callback);
}
function VoteUp( commentid)
{
	SendCommand("UP",commentid,"");
}

function VoteDown( commentid)
{
	SendCommand("DOWN",commentid,"");
}

function Hide( commentid)
{
	SendCommand("HIDE",commentid,"");
}


function PostStory()
{
	if ( mytitle.value =="" )
	{
		mymessage.innerHTML="please type in a title, then submit.";
		return;
	}
	if ( mytitle.value.length >255)
	{
		mymessage.innerHTML="title too long.";
		return;
	}
	if ( mydesc.value =="" )
	{
		mymessage.innerHTML="please type in a description, then submit.";
		return;
	}
	if ( mydesc.value.length >1000)
	{
		mymessage.innerHTML="description too long.";
		return;
	}
	if ( mylink.value =="" )
	{
		mymessage.innerHTML="please type in a link, then submit.";
		return;
	}
	if ( mylink.value.length >15)
	{
		// now we use server side validation.
		//mymessage.innerHTML="link too long.";
		//return;
	}
	SendCommand("POST",encodeURI (mytitle.value) ,encodeURI ( mydesc.value),encodeURI (mylink.value) );
}

</script>

<?
$query = "SELECT *, date_format(datecreated,'%Y-%m-%d %H:%i') as date1 FROM critizethis_story where categoryid = '$categoryid' and published=1 order by id desc limit 0,1";

$result = mysql_query($query,$db) or die (" died on query: ". $query);
?>


<table width="100%"><tr>
<td colspan="10" width="100%"><?
if ( $this_usertype =="Administrator" ||  $this_usertype =="Super Administrator")
{
	echo "<a href=\"pending_stories.php\"><b>Pending Stories</b></a><p>\r";
}
?></td></tr><tr>

<td id="headings" valign="top" width="50%">
<table><tr><td ><img src="http://therealnews.com/scripts/collapsedivs/images/latest_story.gif"></td></tr>

<?

$count=0;
while ($myrow = mysql_fetch_array($result))
{
        $story_id = stripslashes($myrow["id"]);
        $story_desc = stripslashes($myrow["description"]);
        $story_title = stripslashes($myrow["title"]);
        $story_datecreated = stripslashes($myrow["date1"]);
        $story_link= stripslashes($myrow["link"]);

//        if ( $count %2 == 0 ) 
//		echo "<tr>";
?>
<tr>
<td valign=top>

<a href='criticizethis_story.php?id=<?=$story_id?>'><img width=450 height=300 border=0 src="http://img.youtube.com/vi/<?=$story_link?>/0.jpg"></a>
<p><b><a href='criticizethis_story.php?id=<?=$story_id?>'><?=$story_title?></a></b>
<br><br><br></td>
</tr>
<?
//        if ( $count %2 == 1 ) 
//		echo "<td colspan=2 height=20></td></tr>\r";
        $count++;
}

//if ( $count %2 == 1 ) 
//	echo "<td colspan=2 height=20></td></tr>\r";


?>


</table></td><td valign="top" >

<img src="http://therealnews.com/scripts/collapsedivs/images/post_story.gif"><p>

<input type="text" value="Title"  onfocus="if
(this.value==this.defaultValue) this.value='';" onBlur="if(this.value=='')this.value='Title';" id=mytitle size="43" ><p>

<textarea name="mydesc" id="mydesc"  onfocus="if
(this.value==this.defaultValue) this.value='';" onBlur="if(this.value=='')this.value='Description';" cols=40 rows=3>Description</textarea><p>

<input type="text" value="Link"  onfocus="if
(this.value==this.defaultValue) this.value='';" onBlur="if(this.value=='')this.value='Link';" id="mylink" size="43" ><p>

<input type="image" src="http://nocache.therealnews.com/scripts/collapsedivs/images/submit_red.gif" value="Submit Your Story" onclick='PostStory()' /><div id=mymessage></div>
<p>
<img src="http://therealnews.com/scripts/collapsedivs/images/top_story.gif"><p>
<?
$query = "SELECT a.*,date_format(a.datecreated,'%Y-%m-%d %H:%i') as date1,ifnull(count( b.id ),0)as commentcount FROM critizethis_story a left join comment b on a.id=b.eventid where a.categoryid = '$categoryid' and a.published=1 group by a.id order by commentcount desc, a.id desc limit 0,5";

//$query = "SELECT *, date_format(datecreated,'%Y-%m-%d %H:%i') as date1 FROM critizethis_story where categoryid = '$categoryid' and published=1 order by id desc limit 0,10";

$result = mysql_query($query,$db) or die (" died on query: ". $query);
while ($myrow = mysql_fetch_array($result))
{

        $story_id = stripslashes($myrow["id"]);
        $story_desc = stripslashes($myrow["description"]);
        $story_title = stripslashes($myrow["title"]);
        $story_datecreated = stripslashes($myrow["date1"]);
        $story_link= stripslashes($myrow["link"]);


	echo "<a href=\"criticizethis_story.php?id=$story_id\"><b>$story_title</b></a><p>\r";
	
}

?>
<a href="latest_stories_all.php">see all stories</a>
</td></tr>

<tr><td valign="top" colspan="2">
<img src="http://therealnews.com/scripts/collapsedivs/images/latest_critique.gif"><p>
<?
$query = "SELECT a.id,a.title,b.comment,date_format(b.datecreated,'%Y-%m-%d %H:%i') as date1 FROM critizethis_story a join comment b on a.id=b.eventid where a.categoryid = '$categoryid' and a.published=1 and b.published =1 order by b.datecreated desc, a.id desc limit 0,10";


$result = mysql_query($query,$db) or die (" died on query: ". $query);
while ($myrow = mysql_fetch_array($result))
{

        $story_id = stripslashes($myrow["id"]);
        $comment = stripslashes($myrow["comment"]);
        $story_title = stripslashes($myrow["title"]);
        $story_datecreated = stripslashes($myrow["date1"]);

	echo "<a href=\"criticizethis_story.php?id=$story_id\"><b>$story_title</b><br></a> $comment<p><hr class='dots' align=\"left\" width=\"90%\">\r";
}
?>

</td>
</tr></table>
</body>
</html>
